<template>
  <Modal v-model="visible"
         title="编辑字典分类"
         @on-cancel="closeModal"
         footer-hide
         :width="480">
    <Form ref="form" :model="form" :rules="rules"
          :label-width="100">
      <FormItem label="分类代码" prop="typeCode">
        <Input v-model="form.typeCode" placeholder="请输入分类代码"></Input>
      </FormItem>
      <FormItem label="分类名称" prop="typeName">
        <Input v-model="form.typeName" placeholder="请输入分类名称"></Input>
      </FormItem>
      <FormItem label="排序" prop="sort">
        <InputNumber :min="0" :step="1" v-model="form.sort"></InputNumber>
      </FormItem>
      <FormItem>
        <Button type="primary" :loading="submitting" @click="submit">提交</Button>
      </FormItem>
    </Form>
  </Modal>
</template>

<script>
import { detailType, updateType } from '../../../../apis/system/dictType';

export default {
  name: 'createType',
  data() {
    return {
      visible: false,
      id: '',
      form: {
        typeCode: undefined,
        typeName: undefined,
        sort: 0,
      },
      rules: {
        typeCode: [
          { required: true, message: '请输入分类代码', trigger: 'blur' }
        ],
        typeName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      submitting: false
    };
  },
  methods: {
    openModal(id) {
      this.visible = true;
      this.id = id;
      this.initData();
    },
    initData() {
      detailType(this.id, (responseData) => {
        this.form.typeCode = responseData.typeCode;
        this.form.typeName = responseData.typeName;
        this.form.sort = responseData.sort;
      });
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitting = true;

          updateType(this.id, {
            typeCode: this.form.typeCode,
            typeName: this.form.typeName,
            sort: this.form.sort
          }, () => {
            this.submitting = false;

            this.$Message.success('保存成功');
            this.closeModal();
            this.$refs.form.resetFields();
            this.$emit('success');
          }, () => {
            this.submitting = false;
          });
        }
      });
    },
    closeModal() {
      this.visible = false;
    }
  }
};
</script>

<style scoped>

</style>
